"""
sql orm 执行器
"""

from sql import Table
from sql.aggregate import Count, Literal


class SqlAction(object):
    """
    https://pypi.org/project/python-sql/
    处理来自python-sql的SQL语句
    """

    def total(self, table: Table, session, where=None):
        return self.fetchone(table, session, where=where, fields=(Count(Literal(1)),)).get("COUNT(1)")

    def format_SQL(self, SQL):
        """
        :param SQL:
        :return:
        """
        query, data = tuple(SQL)
        return query.replace("\"", ""), data

    def fetchone(self, table: Table, session, where=None, fields=tuple(), group_by=None, order_by=None):
        sqlobj = table.select(*fields, limit=1, offset=0)
        sqlobj.where = where
        sqlobj.group_by = group_by
        sqlobj.order_by = order_by
        sql, data = self.format_SQL(sqlobj)
        session.execute(sql, data)
        return session.fetchone()

    def fetchmany(self, table: Table, session, where=None, fields=tuple(), limit=10, offset=0, group_by=None,
                  order_by=None):
        sqlobj = table.select(*fields, limit=limit, offset=offset)
        sqlobj.where = where
        sqlobj.group_by = group_by
        sqlobj.order_by = order_by
        sql, data = self.format_SQL(sqlobj)
        session.execute(sql, data)
        return session.fetchall()

    def update(self, table: Table, columns, values, session, where=None):
        sqlobj = table.update(columns=columns, values=values)
        sqlobj.where = where
        sql, data = self.format_SQL(sqlobj)
        session.execute(sql, data)

    def insert(self, table: Table, columns, values, session):
        sqlobj = table.insert(columns=columns, values=values)
        sql, data = self.format_SQL(sqlobj)
        session.execute(sql, data)
        _id = session.lastrowid
        return _id
